package com.yuke.cloud.service.uac.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yuke.cloud.common.base.enums.ErrorCodeEnum;
import com.yuke.cloud.common.util.PublicUtil;
import com.yuke.cloud.service.api.uac.exceptions.UacBizException;
import com.yuke.cloud.service.uac.dto.AuthUserDto;
import com.yuke.cloud.service.uac.dto.UserRegisterDto;
import com.yuke.cloud.service.uac.entity.AccUser;
import com.yuke.cloud.service.uac.service.AccUserService;
import com.yuke.cloud.service.uac.service.AuthWxService;
import com.yuke.cloud.service.uac.service.WxMiniService;
import com.yuke.cloud.service.uac.utils.JwtTokenUtils;
import com.yuke.cloud.service.uac.weixin.JsonUtils;
import com.yuke.cloud.service.uac.weixin.JwtHelper;
import com.yuke.cloud.service.uac.weixin.WechatConstants;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.task.TaskExecutor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Service
public class AuthWxServiceImpl  implements AuthWxService {
    @Resource
    private AccUserService accUserService;
    @Resource
    private WxMiniService wxMiniService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private TaskExecutor taskExecutor;

    private JwtTokenUtils jwtTokenUtils;

    @Value("${yuke.security.social.weixin.app-id}")
    private String appId;
    @Value("${yuke.security.social.weixin.app-secret}")
    private String secret;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AuthUserDto code2openid(AuthUserDto authUserDto) {

        //authType=1代表是微信登录
        System.out.println("appID="+appId);
        System.out.println("secret="+secret);
        appId = "wx175eed43ff059b53";//"wx9eb087df9683c10d";
        secret="b72088773d79bac3c2553a305a45cb4e";//"3ebcb1efea7d6b77ddf8b09884716c14";
        if (!PublicUtil.isEmpty(authUserDto.getAuthType()) && authUserDto.getAuthType() == 1) {
            JSONObject jsonObject = wxMiniService.authCode2Session(appId, secret, authUserDto.getCode());
            if (jsonObject == null) {
                throw new RuntimeException("调用微信端授权认证接口错误");
            }
            System.out.println("微信调用CODE2Session返回："+JSONObject.toJSONString(jsonObject));
            String openId = jsonObject.getString("openid");
            String sessionKey = jsonObject.getString("session_key");

            redisTemplate.opsForValue().set(openId, sessionKey, 30, TimeUnit.MINUTES);

            if (PublicUtil.isEmpty(openId)) {
                throw new UacBizException(ErrorCodeEnum.UAC10011004,jsonObject.getString("errcode"), jsonObject.getString("errms"));
            }
            authUserDto.setOpenId(openId);
            //authUserDto.setSessionKey(sessionKey);
            //判断用户表中是否存在该用户，不存在则进行解密得到用户信息，并进行新增用户
            AccUser resultUser = accUserService.findByOpenId(openId);
            if (resultUser != null) {
                authUserDto.setAccUser(resultUser);
                String token = JwtHelper.createJWT("wechat", JsonUtils.toJson(authUserDto.getAccUser()), WechatConstants.JWT_TTL);
                if (PublicUtil.isEmpty(token)) {
                    throw new RuntimeException("生成token错误");
                }
                //authUserDto.setToken(token);
            }
        }
        System.out.println(authUserDto);
        return authUserDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AuthUserDto wxRegist(AuthUserDto authUserDto, HttpServletRequest request) {
                //authType=1代表是微信登录
        if (authUserDto==null || authUserDto.getOpenId() == null ) {
            return authUserDto;
        }
        if (!PublicUtil.isEmpty(authUserDto.getAuthType()) && authUserDto.getAuthType() == 1) {
            //判断用户表中是否存在该用户，不存在则进行解密得到用户信息，并进行新增用户
            AccUser resultUser = accUserService.findByOpenId(authUserDto.getOpenId());
            if (resultUser == null) {
                AccUser user = accUserService.findByMobileNo(authUserDto.getMobileNo());
                if (user != null){
                    user.setOpenId(authUserDto.getOpenId());
                    if (authUserDto.getReferenceShopId() != null && authUserDto.getReferenceShopId() > 0){
                        user.setReferenceShopId(authUserDto.getReferenceShopId());
                    }
                    authUserDto.setAccUser(user);
                    taskExecutor.execute(() -> accUserService.update(user));
                }else{
                    AccUser accuser = new AccUser();
                    accuser.setUserName(authUserDto.getLoginName());
                    accuser.setLoginName(authUserDto.getLoginName());
                    accuser.setMobile(authUserDto.getMobileNo());
                    accuser.setUserPassword(authUserDto.getPassword());
                    authUserDto.setAccUser(accuser);

                    UserRegisterDto userRegisterDto = new UserRegisterDto();
                    userRegisterDto.setLoginName(authUserDto.getLoginName());
                    userRegisterDto.setMobileNo(authUserDto.getMobileNo());
                    userRegisterDto.setOpenId(authUserDto.getOpenId());
                    userRegisterDto.setLoginPwd(authUserDto.getPassword());
                    userRegisterDto.setConfirmPwd(authUserDto.getPassword());
                    userRegisterDto.setRegisterSource(authUserDto.getRegisterSource());
                    accUserService.register(userRegisterDto);

                }


            } else {
                //去登陆
                authUserDto.setAccUser(resultUser);
            }

            //创建token
            //String token = jwtTokenUtils.createToken(openId,JSON.toJSONString(authUserDto));
//            String token = JwtHelper.createJWT("yuke-client-uac", JsonUtils.toJson(authUserDto.getAccUser()), WechatConstants.JWT_TTL);
//            if (PublicUtil.isEmpty(token)) {
//                throw new RuntimeException("生成token错误");
//            }
//            authUserDto.setToken(token);

            //保存token

        }
        return authUserDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AuthUserDto wxLogin(AuthUserDto authUserDto, HttpServletRequest request) {
        return authUserDto;
    }
}
